package com.example.ruiji.filter;

import com.example.ruiji.utils.token.JwtToken;
import com.example.ruiji.utils.token.MyTokenUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.thymeleaf.util.ArrayUtils;
import org.thymeleaf.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.*;
import java.lang.invoke.VarHandle;
import java.util.Arrays;

/**
 * Author:BaiYiChen
 * Date:2022/5/2 21:03
 *
 * @author BaiYiChen
 */
public class JwtTokenFilter extends AuthenticatingFilter {
  @Override
  protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
    HttpServletRequest request = WebUtils.toHttp(servletRequest);
    String header = request.getHeader(MyTokenUtils.ACCESS_TOKEN);
    String parameter = request.getParameter(MyTokenUtils.ACCESS_TOKEN);
    Cookie[] cookies = request.getCookies();
    String token = null;
    for (Cookie cookie : cookies) {
      if (cookie.getName().equals(MyTokenUtils.ACCESS_TOKEN)) {
        token = cookie.getValue();
        break;
      }
    }
    if (!StringUtils.isEmpty(header)) {
      return new JwtToken(header);
    } else if (!StringUtils.isEmpty(parameter)) {
      return new JwtToken(parameter);
    } else if (token != null) {
      return new JwtToken(token);
    }
    return null;
  }
  
 //是否放行
  @Override
  protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
    HttpServletRequest request = WebUtils.toHttp(servletRequest);
    String header = request.getHeader(MyTokenUtils.ACCESS_TOKEN);
    String parameter = request.getParameter(MyTokenUtils.ACCESS_TOKEN);
    Cookie[] cookies = request.getCookies();
    String token = null;
    try {
      for (Cookie cookie : cookies) {
        if (cookie.getName().equals(MyTokenUtils.ACCESS_TOKEN)) {
          token = cookie.getValue();
          break;
        }
      }
    } catch (Exception e) {
    
    }
    if (!StringUtils.isEmpty(header)) {
      getSubject(servletRequest, servletResponse).login(new JwtToken(header));
      return true;
    } else if (!StringUtils.isEmpty(parameter)) {
      getSubject(servletRequest, servletResponse).login(new JwtToken(parameter));
      return true;
    } else if (!StringUtils.isEmpty(token)) {
      getSubject(servletRequest, servletResponse).login(new JwtToken(token));
      return true;
    }
//    request.getRequestDispatcher("/login").forward(servletRequest, servletResponse);
    WebUtils.toHttp(servletResponse).sendRedirect("/login");
    return false;
  }
  
}
